import dayjs from "dayjs";
import { array } from "joi";
import { socket } from "~/components/socket";

import { useDisciples } from "~/store/useDisciples";

// window.Message({
//   uuid: uuidv4(),
//   message: 'Hello World! {name},{name}',
//   name: "A",
//   nameColor: "#000",
//   level: 'info',
// })
const mySymbol = Symbol("GoodMessage");
export interface Message {
  uuid: string;
  message: string;
  sendPerson: string;
  sendId: string;
  [key: string]: string;
  level: "info" | "error";
  [mySymbol]: object;
}
function isMessage(obj: any): obj is Message {
  //类型守卫
  // 基础属性校验
  const hasRequiredFields =
    typeof obj.uuid === "string" &&
    typeof obj.message === "string" &&
    typeof obj.sendPerson === "string" &&
    typeof obj.sendId === "string" &&
    ["info", "error"].includes(obj.level);

  // Symbol 属性校验（需提前定义 mySymbol）
  const hasSymbol = mySymbol in obj && typeof obj[mySymbol] === "object";

  // 字符串索引签名校验（排除已知属性）
  const otherKeys = Object.keys(obj).filter(
    (key) => !["uuid", "message", "sendPerson", "sendId", "level"].includes(key)
  );
  const isValidExtraFields = otherKeys.every(
    (key) => typeof obj[key] === "string"
  );

  return hasRequiredFields && hasSymbol && isValidExtraFields;
}
// 扩展 logger.info 方法
window.Message = (...args: Message[] | string[]) => {
  const auth = useAuth();
  let timestampedArgs: string;
  if (!isMessage(args[0])) {
    timestampedArgs = `${dayjs().format("YYYY-MM-DD HH:mm:ss")} ${
      auth.user.name
    }说：${
      typeof args[0] === "string" ? args[0] : (args[0] as Message).message
    }`;
  } else {
    // 添加时间戳到每条日志消息前

    let arr = args[0].message.match(/\{(.*?)\}/g);
    console.log(arr);
    arr?.map((ite: string) => {
      const key = ite.slice(1, -1);
      if ((args[0] as Message).GoodMessage) {
        //需要等颜色登记
        // args[0].message=args[0].message.replaceAll(ite,`<font style="color:${args[0][key].GoodMessage};">${args[0][key].GoodMessage.name}</font>`)
      } else {
        (args[0] as Message).message = (args[0] as Message).message.replaceAll(
          ite,
          `<font style="color:${
            (args[0] as Message)[key + "Color"] || "#000"
          };">${(args[0] as Message)[key] || (args[0] as Message)}</font>`
        );
      }
    });
    timestampedArgs = args
      .map(
        (arg) =>
          `${dayjs().format("YYYY-MM-DD HH:mm:ss")} ${auth.user.name}: ${
            (arg as Message).message
          }`
      )
      .join(" ");
  }

  if (socket) {
    socket.emit("index", args[0]);
  }
  const consoleElement = document.querySelector(".console");
  // 如果在浏览器环境中，且存在 document 对象
  if (typeof document !== "undefined" && document && consoleElement) {
    // 创建并添加日志消息到 DOM 中
    const child = document.createElement("div");
    child.innerHTML = timestampedArgs;
    if (consoleElement) {
      consoleElement.appendChild(child);
    }
  }

  // 调用原始的 logger.info 方法，并传入修改后的参数
  return console.info(Array.from(timestampedArgs).join(""));
};

export default defineNuxtPlugin(() => {});
